﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Mrc.SqlSurging.DBContext;
using Mrc.Entities;
using SqlSugar;
using System.Linq;
using Mrc.Domain.Dto;
using Mrc.Domain.IModule;
using Mrc.Common;

namespace Mrc.Domain.Module.Auth
{
    public class UserLoginService : IAccountLogonService<LoginInfoDto>
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginName">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public Task<LoginInfoDto> CheckLogin(string loginName, string password)
        {
            if (loginName.IsNullOrWhiteSpace() || password.IsNullOrWhiteSpace()) throw new MrcException("请输入用户名或密码");
            var db = new SugarClientHelper().GetSqlSugarClient();
            var users = db.Queryable<AppUser,SysUserLogOn>((accounttable, pwdtable) => new object[] { JoinType.Left, accounttable.AccountName == loginName && accounttable.Id == pwdtable.UserId })
                .Select((accounttable, pwdtable) => new { accounttable.Id, accounttable.AccountName, accounttable.State, accounttable.Name, pwdtable.UserPassword, pwdtable.UserSecretkey }).ToList();
            if (!users.Any()) throw new MrcException("用户不存在");
            var user = users.First();
            string encryptPassword = EncryptHelper.EncryptMD5Password(password, user.UserSecretkey);
            if (encryptPassword != user.UserPassword) throw new MrcException("密码不正确");
            return Task.FromResult(new LoginInfoDto
            {
                AccountName = user.AccountName,
                Name = user.Name,
                State = user.State
            });
        }
    }
}